from django.views.generic import View
from libs import json_response, JsonParser, Argument
from apps.workorder.models import Template
from apps.account.models import Role
from libs import human_datetime, AttrDict

# Create your views here.


class TemplateView(View):
    def get(self, request):
        register_id = request.GET.get('id')
        if register_id:
            return json_response(Template.objects.get(pk=register_id))
        registers = Template.objects.filter(deleted_by_id__isnull=True)

        return json_response(registers)

    def post(self, request):
        form, error = JsonParser(
            Argument('id', type=int, required=False),
            Argument('name', help='请输入流程模板名称'),
            Argument('flow', help='请输入流程模板'),
            Argument('desc', required=False),
        ).parse(request.body)

        if error is None:
            print(form)
            if form.id:
                # 如果传的参数带id,则更新
                Template.objects.filter(pk=form.pop('id')).update(**form)
            elif Template.objects.filter(name=form.name, deleted_by_id__isnull=True).exists():
                # register名称唯一，如果已存在相同的register名称则报错
                return json_response(error=f'已存在的流程模板名称【{form.name}】')
            else:
                # 新建Register记录
                register = Template.objects.create(created_by=request.user, **form)
                if request.user.role:
                    request.user.role.add_host_perm(register.id)
        return json_response(error=error)

    def delete(self, request):
        form, error = JsonParser(
            Argument('id', type=int, help='请指定操作对象')
        ).parse(request.GET)
        if error is None:
            Template.objects.filter(pk=form.id).update(
                deleted_at=human_datetime(),
                deleted_by=request.user,
            )
        return json_response(error=error)
